package cn.joybreeze.common.handler;

import cn.joybreeze.common.result.R;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CustomAuthenticationEntryPoint
 * @Description 抛出异常让全局异常捕获，AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 * @Author Kjwaa
 * @Email 1135274290@qq.com
 * @Date 2021/10/4 20:38
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/javascript;charset=utf-8");
        response.getWriter().print(JSONObject.toJSONString(R.error("请登录认证")));
    }
}
